package com.chansos.dubbogo.ui;

import com.chansos.dubbogo.common.Registry;
import com.chansos.dubbogo.project_generator.GoGenericTemplate;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBPanel;
import com.intellij.ui.components.JBScrollPane;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class GoNewProjectPanel {
    private static final List<GoGenericTemplate> selections = GoGenericTemplate.getSelections();
    private static final DefaultListModel<GoGenericTemplate> templateListModel = JBList.createDefaultListModel(selections);
    private static final JBList<GoGenericTemplate> templateList = new JBList<>(templateListModel) {{
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        setSelectedIndex(0);
        addListSelectionListener(e -> GoNewProjectPanel.update());
        setCellRenderer(new ColoredListCellRenderer<>() {

            @Override
            protected void customizeCellRenderer(@NotNull JList<? extends GoGenericTemplate> list, GoGenericTemplate value, int index, boolean selected, boolean hasFocus) {
                setIcon(value.getIcon());
                setIconTextGap(8);
                append(value.getName());
            }

        });
    }};

    private static final RegistriesGroup registriesGroup = new RegistriesGroup();
    private static final ComponentsGroup componentsGroup = new ComponentsGroup();

    public final static JBPanel<?> panel = new JBPanel<>() {{
        setLayout(new BorderLayout());
        JBLabel label = new JBLabel();
        label.setText("Dubbo Go template");
        label.setPreferredSize(new Dimension(320, 32));
        add(label, BorderLayout.NORTH);

        JBScrollPane scrollablePanel = new JBScrollPane(templateList);
        add(scrollablePanel, BorderLayout.CENTER);

        JBPanel<?> bottom = new JBPanel<>(new BorderLayout());
        bottom.add(registriesGroup, BorderLayout.NORTH);
        componentsGroup.setVisible(false);
        bottom.add(componentsGroup, BorderLayout.CENTER);
        scrollablePanel = new JBScrollPane(bottom);
        scrollablePanel.setPreferredSize(new Dimension((int) scrollablePanel.getPreferredSize().getWidth(), 400));
        add(scrollablePanel, BorderLayout.SOUTH);
    }};

    public static GoGenericTemplate getSelection() {
        return selections.get(templateList.getSelectedIndex());
    }

    public static Registry getRegistry() {
        return registriesGroup.getSelection();
    }

    public static ComponentsGroup.ComponentConfigs getComponents() {
        return componentsGroup.getComponentConfigs();
    }

    public static void update() {
        componentsGroup.setVisible(getSelection() == GoGenericTemplate.EmptyProject);
    }
}
